new Vue({
    el: '#app',
    mixins: [Query],//组件配置文件，路径/utils/components.js
    data() {
        return {
            form: {//查询筛选
                value: '',
                value2: '-', // 状态：'-'全部、'0'待审核、'2'已通过、'3'拒绝
                PageNumber: 1, //页码
                RowAmount: 20,
                // Condition 两参：关键词,状态（后端 SQL: Article_Name LIKE ? AND Row_Status LIKE ?）
                Condition: utf8ToBase64(`%%,%%`),
            },
            dialogInvoiceViewVisible: false,
            invoiceViewList: [],
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.getColumn(); //查询表头数据
         * 2.this.getList(this.form); //查询表格数据
         * 3.this.getTreeData();//查询树
         */
    },
    methods: {
        isRejected(row) { // 仅拒绝状态显示“修改并重新提交”
            const s = (row && row.Row_Status) || '';
            return s !== '0' && s !== '1' && s !== '2';
        },
        handleCommand(command, row) { // 更多操作分发
            try {
                if (command === 'handleAdd') {
                    this.handleAdd(row);
                } else if (command === 'handleModifyResubmit') {
                    this.handleModifyResubmit(row);
                } else if (command === 'openInvoiceViewer') {
                    this.openInvoiceViewer(row);
                }
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        handleSerach() { //筛选
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        // 状态切换：更新 Condition 第二参数并刷新列表
        handleTabsClick() {
            const val = this.form.value2;
            const status = (val === '-' || val === '' || val == null) ? '%%' : val;
            this.form.PageNumber = 1;
            this.form.Condition = utf8ToBase64(`%${this.form.value}%,${status}`);
            this.getList(this.form);
        },
        handleAdd(row) { // 确认合同（以甲方身份进入销售合同详情）
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Supply_Order_SerialNumber || row.Trading_Apply_SerialNumber || row[primaryKey];
                if (!applyId) {
                    this.$message.error('未找到申请流水号，无法跳转合同详情');
                    return;
                }
                const url = `../sales_order/contract_details.html?applyId=${encodeURIComponent(applyId)}`;
                window.location.href = url;
            } catch (error) {
                console.error(error);
                this.$message({ message: '系统错误，请联系开发者!', type: 'error' });
            }
        },
        async openInvoiceViewer(row) {
            try {
                const orderSerial = row.Supply_Order_SerialNumber || '';
                if (!orderSerial) {
                    this.$message.error('未找到订单编号');
                    return;
                }
                const res = await generalApi.generalQueryByTableName({ Data: 'supply_order_invoice', Condition: `Supply_Order_SerialNumber='${orderSerial.replace(/'/g, "''")}'` });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.invoiceViewList = (arr || []).map(i => ({ url: (imageApi || '') + String(i.Picture_URL || '') })).filter(j => j.url);
                this.dialogInvoiceViewVisible = true;
            } catch (e) {
                console.error(e);
                this.$message.error('系统错误，请联系开发者!');
            }
        },
        handleShow(row) { // 查看购买记录（按申请流水号筛选）
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Supply_Order_SerialNumber || row.Trading_Apply_SerialNumber || row[primaryKey];
                if (!applyId) {
                    this.$message({ message: '未获取到申请流水号', type: 'error' });
                    return;
                }
                window.location.href = `../supply_order/details.html?applyId=${encodeURIComponent(applyId)}&fromPage=supply_order`;
            } catch (error) {
                console.error(error);
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            }
        },
        handleModifyResubmit(row) { // 修改并重新提交：跳转到提交页的修改模式
            try {
                const { primaryKey } = $('#table').data('options');
                const applyId = row.Supply_Order_SerialNumber || row[primaryKey];
                if (!applyId) {
                    this.$message({ message: '未获取到申请流水号', type: 'error' });
                    return;
                }
                window.location.href = `./add.html?action=Modify&nodeKey=${encodeURIComponent(applyId)}`;
            } catch (error) {
                console.error(error);
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            }
        },
        handleCancel(row) {//作废
            this.$confirm('警告！此操作将作废该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                try {
                    const { tableName, primaryKey } = $('#table').data('options');
                    httpRequest({
                        url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                        data: {
                            Data: tableName,
                            Condition: `${primaryKey}='${row[primaryKey]}'`
                        }
                    }).then(data => {
                        if (data.length == 1) {
                            data[0].Row_Status = '2';
                            let lJSONObject_Modify = new Object();
                            lJSONObject_Modify[tableName] = data;
                            //组合
                            let lJSONObject_DataSet = {
                                Modify: lJSONObject_Modify, Add: {}
                            };
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: getRelativePath(),
                                Operation_Description: '作废数据',
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            httpRequest({
                                contentType: 'JSON',
                                url: '/generalBusiness/generalSaveByRequestBody',
                                data: JSON.stringify({
                                    Data: lJSONObject_DataSet
                                })
                            }).then(res => {
                                if (res.Status == "success") {
                                    this.getList(this.form);
                                    this.$message.success("作废成功");
                                } else {
                                    this.$message.error("作废失败，请重试！");
                                }
                            }).catch(xhr => {
                                this.$message({
                                    message: '系统错误，请联系开发者!',
                                    type: 'error'
                                })
                            })
                        }
                    }).catch(xhr => {
                        this.$message({
                            message: '系统错误，请联系开发者!',
                            type: 'error'
                        })
                    })
                } catch (error) {
                    console.error(error);
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                }
            }).catch(() => { });
        }
    }
})
